package com.lyy.utils;

import com.lyy.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * 获取处理业务的bean的工厂
 */
@Component("businessBeanFactory")
public class BusinessBeanFactory {
    //注入service对象
    @Autowired
    private IAccountService accountService;

    //注入事务管理器对象
    @Autowired
    private TransactionManager transactionManager;

    /**
     * 创建用动态代理增强的IAccountService对象
     * @return
     */
    public IAccountService createAccountService(){
        return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                try {
                    //开启事务
                    transactionManager.startTransaction();
                    //使用反射执行原来的业务方法
                    Object result = method.invoke(accountService, args);
                    //提交事务
                    transactionManager.commit();
                    return result;
                } catch (Exception e){
                    e.printStackTrace();
                    //回滚事务
                    transactionManager.rollBack();
                }
                return null;
            }
        });
    }
}
